var latests = "";


function view_download(download_id){
       document.location.href="/downloads/"+download_id+"/";
}

function alter_priority(download_id, priority){
	var request = new Ajax.Request('/downloads/'+download_id+'/alter_priority', { method:'get',
                                parameters: {enc: "json", priority: priority},
                                onSuccess: function(transport){
                                        var json = transport.responseText;
                                        obj = json.evalJSON();
                                        //updateDownloadStatus(id,obj);}
                                        get_latests_downloads(10);
                                        }
                                });
        return false;
}

function get_latests_downloads(num){
	 var request = new Ajax.Request('/downloads/latests', { method:'get',
                                parameters: {enc: "json", num: num},
                                onSuccess: function(transport){
                                        var json = transport.responseText;
                                        obj = json.evalJSON();
					check_priority_swap(obj);}
					});
         return false;
}

function check_priority_swap(downloads){

	if (latests == ""){
		latests = downloads;
		return;
	}

	var redraw = 0;
	for (i=0;i<downloads.length && redraw==0;i++){
		if (latests[i].pk != downloads[i].pk){
			redraw = 1;
			return;	
		}
	}

	if (redraw == 1){
		redraw_downloads();
	}

}

function redraw_downloads(){
	var html = "<table border=\"0\" cellpadding=\"10\" cellspacing=\"0\">" +
               "<theader>" +
                        "<td>Name</td>" +
                        "<td>Download</td>" +
                        "<td>Queue date</td>" +
                        "<td>Priority</td>" +
                "</theader>";

	for(i=0;i<latests.length;i++){

		html += "<tr>" +
                        "<td onClick=\"view_download("+ latests[i].pk +")\">" + latests[i].fields.name +
                        "</td>" +
                        "<td onClick=\"view_download("+ latests[i].pk +")\">" + latests[i].fields.url +
                        "</td>" +
                        "<td onClick=\"view_download("+ latests[i].pk +")\">" + latests[i].fields.start_date +
                        "</td>" +
                        "<td>" + 
                                "<img src=\"/static_media/images/icons/2downarrow.png\" onClick=\"alter_priority("+ latests[i].pk +",-1)\"/>&nbsp;&nbsp;" +
                                "<img src=\"/static_media/images/icons/2uparrow.png\" onClick=\"alter_priority("+ latests[i].pk +", 1)\"/>" +
                        "</td>" +
                "</tr>";
	}

	html +="</table>";

	$('latests').update(html);

	
}
